package com.example.badyloans.controller;

import com.example.badyloans.common.ReturnResult;
import com.example.badyloans.pojo.*;
import com.example.badyloans.servlet.*;
import com.example.badyloans.util.PageSupport;
import com.sun.xml.internal.bind.v2.TODO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.sound.midi.Soundbank;
import java.lang.reflect.Array;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @author 啊桥哦
 * @Description:
 * @date 2020-07-14 11:59
 */
@Api("用户资金控制器")
@RestController
public class UserWalletController {
    @Resource
    private TUserWalletService tUserWalletService;
    @Resource
    private TBorrowService tBorrowService;
    @Resource
    private TRepaymentService tRepaymentService;
    @Resource
    private TBidService tBidService;
    @Resource
    private TAccountFlowService tAccountFlowService;

    /**
     * 查询个人资料
     * @param userAccountid
     * @return
     */
    @ApiOperation("查询个人资料")
    @PostMapping(value="/user/wallet/get/{userAccountid}")
    public ReturnResult userwalletlist(@PathVariable String userAccountid){
        if (StringUtils.isEmpty(userAccountid)){
            return ReturnResult.fail("参数不能为空");
        }
        TUserWallet tUserWallet = tUserWalletService.selectByPrimaryKey(userAccountid);
        return ReturnResult.success(tUserWallet,null);
    }

    /**
     * 申请借款
     * @param tBorrow
     * @return
     */
    @PostMapping("finance/borrow/add")
    public ReturnResult borrowadd(TBorrow tBorrow){
        boolean boo=tBorrowService.addBorrow(tBorrow);
        return boo?ReturnResult.succes():ReturnResult.fail("借款失败");
    }

    /**
     *借款分页查询
     * @param loginlog
     * @return
     */
    @PostMapping("finance/borrow/query")
    public ReturnResult borrowquery( loginlog loginlog/*,@RequestParam(required = false) Integer[] borrowStates*/){
        PageSupport page=new PageSupport();
        page.setPageSize(3);
        page.setTotalCount(tBorrowService.count(loginlog.getBorrowStates(),loginlog.getBeginDate(),loginlog.getEndDate())); //查询总记录数
        page.setCurrentPageNo(loginlog.getCurrentPage());
        Integer pageSize=page.getPageSize();       //拿到页大小
        Integer currentPageNo=page.getCurrentPageNo(); //拿到页码
//        List<Integer> lists= Arrays.asList(borrowStates);
        List<TBorrow> list=tBorrowService.selectfenye(loginlog.getBorrowStates(),((currentPageNo-1)*pageSize),pageSize,loginlog.getBeginDate(),loginlog.getEndDate());
            if (list==null){
                return  ReturnResult.fail("没有数据");
            }
        return ReturnResult.success(list,page);
    }

     /**
     * 借款审核
     * @param borrowId
     * @param borrowState
     * @return
     */
    @PostMapping("finance/borrow/audit")
    public ReturnResult borrowaudit(String borrowId,Integer borrowState ){
        TBorrow tBorrow=tBorrowService.selectByPrimaryKey(borrowId);
        if(tBorrow==null){
            return ReturnResult.fail("该数据为空");
        }
        if(StringUtils.isEmpty(borrowId)&&StringUtils.isEmpty(borrowState)){
            return ReturnResult.fail("数据不能为空");
        }
        //如果审核状态为11，为拒绝审核
        if(borrowState.equals(11)){
            tBorrow.setBorrowState(borrowState);
            TUserWallet tUserWallet=tUserWalletService.selectByPrimaryKey(tBorrow.getBorrowUserId());
            tUserWallet.setResidualCreditLine(tUserWallet.getResidualCreditLine()+tBorrow.getBorrowAmount());
            tUserWallet.setCreditLine(tUserWallet.getCreditLine()+tBorrow.getBorrowAmount());
            int c=tUserWalletService.updateByPrimaryKeySelective(tUserWallet);
            //如果审核状态为通过，改为招标中
        }else if(borrowState.equals(12)){
                tBorrow.setBorrowState(20);
                //设置当前时间为开始
                tBorrow.setPublishTime(LocalDateTime.now());
                //设置结束
            tBorrow.setBidDeadline(tBorrow.getPublishTime().plusDays(tBorrow.getBidDays()));
        }
        int count=tBorrowService.updateByPrimaryKeySelective(tBorrow);
        if(count>0){
            return ReturnResult.succes();
        }
        return ReturnResult.fail("审核错误");
    }

    /**
     * 商品展示方法
     * @param id
     * @return
     */
    @GetMapping("finance/borrow/get/{id}")
    public ReturnResult borrowgetid(@PathVariable String id){
        if (StringUtils.isEmpty(id)) {
            return  ReturnResult.fail("参数为空");
        }
        TBorrow tBorrow=tBorrowService.selectByPrimaryKey(id);
        return ReturnResult.success(tBorrow,null);
    }

    /**
     * 商品展示方法1
     * @param loginlog
     * @return
     */
    @PostMapping("finance/repayment/getByBorrowId")
    public ReturnResult repaymentgetBorrId(loginlog loginlog){
        TRepayment tRepayment=tRepaymentService.selectByPrimaryKey(loginlog.getBorrowId());
        return ReturnResult.success(tRepayment,null);
    }

    /**
     * 商品展示方法2
     * @return
     * @param id
     * @param loginlog
     */
    @PostMapping("finance/bid/getByBorrowId/{id}")
    public ReturnResult bidgetbyborrowid(@PathVariable String id,loginlog loginlog){
        if (StringUtils.isEmpty(id)) {
            return  ReturnResult.fail("参数为空");
        }
        PageSupport page=new PageSupport();
        page.setPageSize(2);
        page.setTotalCount(tBidService.count()); //查询总记录数
        page.setCurrentPageNo(loginlog.getCurrentPage());
        Integer pageSize=page.getPageSize();       //拿到页大小
        Integer currentPageNo=page.getCurrentPageNo(); //拿到页码
        List<TBid> tBid=tBidService.selectBYPrimaryKey1(id,((currentPageNo-1)*pageSize),pageSize);
        return ReturnResult.success(tBid,page);
    }

    /**
     * 投标记录查询
     * @param userId
     * @param loginlog
     * @return
     */
    @PostMapping("finance/bid/query")
    public ReturnResult bidquery(@RequestParam String userId,loginlog loginlog){
        List<TBorrow> tBorrow=tBorrowService.selectByPrimaryKeys(userId);
        if (StringUtils.isEmpty(userId)) {
            return  ReturnResult.fail("参数为空");
        }
        PageSupport page=new PageSupport();
        page.setPageSize(2);
        page.setTotalCount(tBorrowService.sum()); //查询总记录数
        page.setCurrentPageNo(loginlog.getCurrentPage());
        Integer pageSize=page.getPageSize();       //拿到页大小
        Integer currentPageNo=page.getCurrentPageNo(); //拿到页码
        List<TBid> tBid=null;
        for (int i=0;i<tBorrow.size();i++){
             tBid=tBidService.selectBYPrimaryKey1(tBorrow.get(i).getId(),((currentPageNo-1)*pageSize),pageSize);
        }
        return ReturnResult.success(tBid,page);
    }

    /**
     * 还款记录查询
     * @param userId
     * @param loginlog
     * @return
     */
    @PostMapping("finance/repayment/query")
    public ReturnResult repaymentquery(@RequestParam String userId, loginlog loginlog){
        if (StringUtils.isEmpty(userId)) {
            return  ReturnResult.fail("参数为空");
        }
        PageSupport page=new PageSupport();
        page.setPageSize(5);
        page.setTotalCount(tRepaymentService.sum(userId)); //查询总记录数
        page.setCurrentPageNo(loginlog.getCurrentPage());
        Integer pageSize=page.getPageSize();       //拿到页大小
        Integer currentPageNo=page.getCurrentPageNo(); //拿到页码
        List<TRepayment> tRepayments=null;
        tRepayments=tRepaymentService.selectBypriment(userId,((currentPageNo-1)*pageSize),pageSize);
        return ReturnResult.success(tRepayments,page);
    }

    /**
     * 还款功能
     * @return
     */
    @PostMapping("finance/repayment/repay")
    public ReturnResult repaymentrepay(@RequestParam(required = false) String userId,@RequestParam(required = false) String id){
     /*   id: 0b7076aba3304423b2823824cb329385
        userId: 245ba4004b384fafb52c41507539e21c*/
        TRepayment tRepayment=tRepaymentService.selectByPrimaryKey(id);
        //  1.1  借款人每次还款完成之后，增加本次还款金额等额的授信额度，并生成一条流水记录
        TUserWallet tUserWallet=tUserWalletService.selectByPrimaryKey(userId);
        //判断是否逾期
        if(tRepayment.getDeadline().compareTo(LocalDateTime.now())>0){
            tRepayment.setState(1);
            tRepaymentService.updateByPrimaryKeySelective(tRepayment);
        }
        tUserWallet.setAvailableAmount(tUserWallet.getAvailableAmount()-tRepayment.getTotalAmount());
        tUserWallet.setResidualCreditLine(tUserWallet.getResidualCreditLine()+tRepayment.getTotalAmount());
        tUserWalletService.updateByPrimaryKeySelective(tUserWallet);
        //把当前状态改为已还
        tRepayment.setState(3);
        tRepaymentService.updateByPrimaryKeySelective(tRepayment);
        //生成还款流水
        TAccountFlow tAccountFlow=new TAccountFlow();
        tAccountFlow.setAccountId(userId);
        tAccountFlow.setAmount(tRepayment.getTotalAmount());
        tAccountFlow.setFlowType(23);
        tAccountFlow.setAvailableAmount(tUserWallet.getAvailableAmount());
        tAccountFlow.setFreezeAmount(tUserWallet.getFreezeAmount());
        tAccountFlow.setRemark("还款成功,还款金额是:"+tRepayment.getTotalAmount()*0.01+"元");
        tAccountFlow.setCreateTime(LocalDateTime.now());
        int insert=tAccountFlowService.insertSelective(tAccountFlow);
        if (insert>0) {
            return ReturnResult.succes();
        }else{
            return ReturnResult.fail("还款失败，余额不足。。。。。");
        }

    }

}
